//could be set by a cookie or saved user info if sytem usees login
var BOARD_HEIGHT= 400;
var BOARD_WIDTH= 900;
function writeMessage(messageLayer, message){
    var context = messageLayer.getContext();
    messageLayer.clear();
    context.font = "18pt Calibri";
	context.fillStyle = "black";
	context.fillText(message, 10, 25);
}

function getMousePos(daStage){
	return daStage.getMousePosition();
}



$('document').ready(function() {
	//stage, layers and shapes
	var stage;
	var layerStack = new Array();
	var shapeStack = new Array();
	var redoStack = new Array();
	//moose position
	var mouseCurr;
	var mouseDwn;
	var mouseUp;
	// Are we currently drawing?
	var currently_drawing = false;
	var added_temp_shape = false;
	var inital_pos;
	var current_tool;
	var current_shape = 0;
	var current_context;	
	
	//Call the function that sets the stage 
	setStage();
		
	
	function setStage(){
		$('#canvas-container').height(BOARD_HEIGHT+25).width(BOARD_WIDTH);
		$('#whiteboard').height(BOARD_HEIGHT).width(BOARD_WIDTH);
		stage = new Kinetic.Stage("whiteboard", BOARD_WIDTH, BOARD_HEIGHT);
		layerStack.push(new Kinetic.Layer('message'));
		var initial = new Kinetic.Layer('initial');
		layerStack.push(initial);
		stage.add(initial);
	}
	
	//function to add leyers, draw is however not yet implemented to  use
	// this feature, it can only use the latest (top) layer to draw on
	function addLayer(){
		var name = 'layer' + layerStack.length;
		var layer = new Kinetic.Layer(name);
		stage.add(layer);
		layerStack.push(layer);
	}	

		
	stage.on('mousemove', function(e) {
		if (currently_drawing) {
			mouseCurr= getMousePos(stage);
			if (added_temp_shape) {
				var s = shapeStack.pop();
				removeSingle(s.shape); 	//there now is a function for this that utilizes a stack of layers
										//this should not be a problem here because of the stack not changing during 
										//mousemove. complicates undo redo	
			}
			
			if(current_tool.shape != 'pen'){
				var s = newShape(mouseDwn.x, mouseDwn.y, mouseCurr.x, mouseCurr.y, current_tool);
				shapeStack.push(s);
				drawSingle(s.shape);
				added_temp_shape = true;
			}
			else{ //see comments on functions being called in shapes.j
				if(currently_drawing && current_shape === 0){
					current_shape = initiateFreeShape(mouseDwn.x, mouseDwn.y, current_tool);
				}
				else{
					current_shape.shape = extendFreeShape(mouseCurr.x, mouseCurr.y, current_shape.shape);
					shapeStack.push(current_shape);
					drawSingle(current_shape.shape);
					added_temp_shape = true; 
				}
			}
		}
	})
		
	stage.on('mousedown', function(e){
		//check if ctrl is also pressed down and handle that differently
		if(!e.ctrlKey) {
			currently_drawing = true;
			mouseDwn= getMousePos(stage);
			initial_pos = mouseDwn;
			current_tool = UIgetToolSelection();
		}
		else{
			//select the object you are clicking and stuff
			alert("ctrl clicked");
		}	
	})
	
	stage.on('mouseup', function(e){
		//check if ctrl is also pressed down and handle that differently
		if(!e.ctrlKey) {
		if (currently_drawing) {
				currently_drawing = false;
				added_temp_shape = false;
				//finnishing a free shape and draw it
				if(current_shape != 0){
					current_shape.shape = closeFreeShape(current_shape.shape);
					var s = shapeStack.pop();
  					removeSingle(s.shape);
					shapeStack.push(current_shape)
					drawSingle(current_shape.shape);
					current_shape = 0;
			
				}
			}
		}
	})
	
	//Re draws all shapes on the stack 
	//Not used so far
	function drawAll(){
		var top = layerStack.pop();
		for (var i in shapeStack) {
  			var s = shapeStack[i].shape;
  			top.add(s);
  		}
  		stage.add(top);
  		layerStack.push(top);
  	};
  	
	//Draws a shape and commits to the canvas  	
    function drawSingle(s){
	    var top = layerStack.pop();
  		top.add(s);
  		stage.add(top);
  		layerStack.push(top);
	}

	//Removes a single shape from layer and clears it
	function removeSingle(s){
		var top = layerStack.pop();
  		top.remove(s);
		top.clear(); //does this anything??
		layerStack.push(top);
	}
		
	//Resets/clears the whiteboard
	function drawReset(){
		while(layerStack.length > 0){
			var currL = layerStack.pop();
			while(shapeStack.length > 0) {
	 			var s = shapeStack.pop();
	  			currL.remove(s.shape);
	  		}
  			currL.clear();
  			stage.remove(currL);
  		}
  		while(redoStack.length > 0) {
 			var r = redoStack.pop();
  		}
  		setStage();
  	}
  	
  	//undo
  	function drawUndo(){
  		if(shapeStack.length != 0){
  			//fetch latest shape
  			var u = shapeStack.pop();
   			if(layerStack.length >= 1){
  				var layer = layerStack.pop();
  				if(layer.links.length === 0 || layerStack.length === 0){
  					layer = layerStack.pop()
  				}
  				if(layer.getShapes().length > 0 ){
  					layer.remove(u.shape);
  					redoStack.push(u);
  					stage.add(layer);
  					layerStack.push(layer);
  				}
  				else{return;}
  				
  			}
  			else{return;}
  		}
  		else{return;}	
  	}
  	
  	//redo
  	//note: if you do something in between yoy can draw over it with redo
  	//		is that the behaviour we want. also redo hust throws the shape on the top layer
  	function drawRedo(){
  		if(redoStack.length != 0){
  			var r = redoStack.pop();
  			drawSingle(r.shape);
  			shapeStack.push(r);
  		}	
  	}

		/**
		 * makes resizing of the stage possible
		 */
		
    	$('#canvas-container').resizable({
			maxHeight: 1200,
			maxWidth: 1600,
			minHeight: BOARD_HEIGHT + 25,
			minWidth: BOARD_WIDTH,
			start: function(event, ui){
				$('#whiteboard').attr('style','background-color: silver;opacity:0.2;filter:alpha(opacity=20);');
				$('#whiteboard canvas').addClass('canvasResize');
				$('#spinner').removeClass('dsp-none');
			},
			resize: function(event, ui){
				$('#toolbar').width($(this).width() - 15);
				$('#whiteboard').height($(this).height()-27).width($(this).width()-2);
			},
			stop: function(event, ui){
				var width = $(this).width();
				var height = $(this).height();
				stage.setSize(width-2, height-27);
				$('#whiteboard').removeAttr('style');
				$('#whiteboard canvas').removeClass('canvasResize');
				$(this).resizable( "option", "minHeight", height );
				$(this).resizable( "option", "minWidth", width);
				$('#spinner').addClass('dsp-none');
			}
		});
    	
    
    	/*
    	 * event handler for save
    	 * NOT IMPLEMENTED
    	 */
    	$('#btn-save').click(function() {
			return false;
		});
    	
    	/**
    	 * event handler for undo
    	 */
    	$('#btn-undo').click(function() {
			drawUndo();
			return false;
		});
    	/**
    	 * event handler for redo
    	 */
    	$('#btn-redo').click(function() {
			drawRedo();
			return false;
		});
    	
    	   	
		//resets the toolbar to initial settings
		$('#btn-reset').click(function() {
			var c = confirm("Are you sure you want to empty the whiteboard?");
			if(c){
				var obj = {
				     "shape": 'pen'
				    ,"width": '4' 
					,"color": 'black'
					,"fill": 'white'
				}
				UIsetToolSelection(obj);
				var tb = UIgetToolSelection();
				var msg = tb.shape + ', ' + tb.width + ', ' + tb.color + ', ' + tb.fill;
				drawReset();
				$('#actionMsg').empty().html(msg);
				$("#btnset-shapes").buttonset();
			}
			return false;
		});
	
});

